package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {

    @Autowired
    RedisTemplate redisTemplate;


    @Override
    public ResponseResult follow(UserRelationDto dto) {
        // 1. 检验参数
        if (dto.getAuthorApUserId()==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "作者信息出错");
        }

        if (dto.getOperation() == null || dto.getOperation().intValue() != 0 && dto.getOperation().intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "关注类型出错");
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        Integer authorApUserId = dto.getAuthorApUserId();

        try {
            redisTemplate.multi();
            if (dto.getOperation().intValue() == 0) {
                Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId));
                if (score != null) {
                    CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复关注");
                }
                redisTemplate.opsForZSet().add(UserRelationConstants.FOLLOW_LIST + userId,String.valueOf(authorApUserId) , System.currentTimeMillis());
                redisTemplate.opsForZSet().add(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(userId), System.currentTimeMillis());
            } else {
                redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + userId, String.valueOf(authorApUserId));
                redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(userId));
            }

            redisTemplate.exec();
            return ResponseResult.okResult();
        } catch (Exception e) {
            e.printStackTrace();
            redisTemplate.discard();
                throw e;
        }
    }
}
